package cn.com.nes.site.service.crm.customer.impl;

import cn.com.nes.common.annotation.Logs;
import cn.com.nes.common.util.OssUtil;
import cn.com.nes.mybatis.agent.crm.entity.CustomerHouse;
import cn.com.nes.mybatis.agent.crm.entity.Opportunity;
import cn.com.nes.mybatis.agent.ope.entity.CustomerArchive;
import cn.com.nes.mybatis.agent.ope.entity.SaleOrderInfo;
import cn.com.nes.mybatis.agent.ope.mapper.CustomerArchiveMapper;
import cn.com.nes.mybatis.agent.project.entity.ProjectCustomerRelationship;
import cn.com.nes.mybatis.agent.project.entity.TProject;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.entity.dto.product.GGoodsDTO;
import cn.com.nes.site.entity.dto.product.IsSblxNameplateConfigDTO;
import cn.com.nes.site.entity.em.crm.customer.CustomerLevelEnum;
import cn.com.nes.site.entity.em.crm.customer.CustomerNatureEnum;
import cn.com.nes.site.entity.em.crm.customer.CustomerSaveTypeEnum;
import cn.com.nes.site.entity.em.crm.opportunity.OpportunityClassificationEnum;
import cn.com.nes.site.entity.em.crm.opportunity.OpportunityStageEnum;
import cn.com.nes.site.entity.em.crm.opportunity.OpportunityTypeEnum;
import cn.com.nes.site.entity.em.project.ProjectRelationDataTypeEnum;
import cn.com.nes.site.entity.iot.CustomerSurveyExcel;
import cn.com.nes.site.entity.vo.NullVO;
import cn.com.nes.site.entity.vo.crm.CustomerHouseVO;
import cn.com.nes.site.entity.vo.crm.SalePriceDetailVO;
import cn.com.nes.site.entity.vo.crm.SalePriceMasterVO;
import cn.com.nes.site.entity.vo.crm.SaveCustomerVo;
import cn.com.nes.site.entity.vo.crm.archive.GetCustomerArchiveDetailVO;
import cn.com.nes.site.entity.vo.crm.archive.SaveCustomerArchiveVO;
import cn.com.nes.site.entity.vo.crm.sale.GetSaleOrderDeatilsVO;
import cn.com.nes.site.entity.vo.crm.sale.SaleOrderInfoVO;
import cn.com.nes.site.entity.vo.project.ImportGovernmentalCustomerArchiveVO;
import cn.com.nes.site.modules.opportuntiy.OpportunityBusiness;
import cn.com.nes.site.service.crm.customer.CrmCustomerService;
import cn.com.nes.site.service.crm.customer.CustomerArchiveService;
import cn.com.nes.site.service.crm.customer.CustomerHouseService;
import cn.com.nes.site.service.crm.customer.bo.SaveOpportunityBO;
import cn.com.nes.site.service.crm.customer.dto.CustomerArchiveDTO;
import cn.com.nes.site.service.crm.customer.dto.CustomerDTO;
import cn.com.nes.site.service.crm.customer.dto.CustomerHouseDTO;
import cn.com.nes.site.service.crm.opportunity.CrmOpportunityService;
import cn.com.nes.site.service.crm.order.SaleOrderInfoService;
import cn.com.nes.site.service.crm.order.SalePriceService;
import cn.com.nes.site.service.product.GGoodsService;
import cn.com.nes.site.service.product.ProductSeriesAndEnergyService;
import cn.com.nes.site.service.project.ProjectCustomerRelationshipService;
import cn.com.nes.site.service.project.TProjectService;
import cn.com.nes.site.service.system.region.XzqhService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 客户档案业务逻辑层实现
 */
@Slf4j
@Service
@EnableAspectJAutoProxy
public class CustomerArchiveServiceImpl extends ServiceImpl<CustomerArchiveMapper, CustomerArchive> implements CustomerArchiveService {

    @Resource
    private CrmCustomerService crmCustomerService;

    @Resource
    private CustomerHouseService customerHouseService;

    @Resource
    private SaleOrderInfoService saleOrderInfoService;

    @Resource
    private GGoodsService gGoodsService;

    @Resource
    private TProjectService tProjectService;

    @Resource
    private ProductSeriesAndEnergyService productSeriesAndEnergyService;

    @Resource
    private SalePriceService salePriceService;

    @Resource
    private XzqhService xzqhService;

    @Resource
    ProjectCustomerRelationshipService projectCustomerRelationshipService;

    @Resource
    CrmOpportunityService crmOpportunityService;

    @Resource
    private OpportunityBusiness opportunityBusiness;

    private static final BigDecimal DEFAULT_HEATING_LOAD = new BigDecimal(45); // 默认热负荷为 45W

    @Override
    public PageData saveCustomerArchive(SaveCustomerArchiveVO vo) {
        // 设置参数
        CustomerArchive archive = new CustomerArchive();
        if (Objects.isNull(vo.getArchiveId())) {
            archive.setDeleted(false); // 没删除
            archive.setGmtCreate(new Date());
            archive.setGmtCreateId(vo.getOperateUserId());
        }
        archive.setGmtModified(new Date());
        archive.setGmtModifiedId(vo.getOperateUserId());

        archive.setId(vo.getArchiveId());
        archive.setCustomerId(vo.getCustomerSaveVo().getCustomerId());
        archive.setAreaCode(vo.getCustomerSaveVo().getAreaCode());
        archive.setInstallProtocolId(vo.getInstallProtocolId());
        archive.setIdCardNumber(vo.getCustomerSaveVo().getIdCardNo());
        archive.setFamilyLeaderName(vo.getCustomerSaveVo().getMasterName());
        archive.setPhone(vo.getCustomerSaveVo().getPhone());
        archive.setAddress(vo.getCustomerSaveVo().getAddress());
        archive.setHouseNumber(vo.getCustomerSaveVo().getMph());
        archive.setCustomerCode(vo.getCustomerSaveVo().getKhbh());
        archive.setMeterNumber(vo.getCustomerSaveVo().getDbh());
        archive.setSubjectType(vo.getCustomerSaveVo().getYhztxz());
        archive.setLongitude(vo.getCustomerSaveVo().getJd());
        archive.setLatitude(vo.getCustomerSaveVo().getWd());
        archive.setInstallWorkOrderId(vo.getInstallSaveVo().getWorkOrderInstallId());
        archive.setBuildInfoId(vo.getBuildingSaveVo().getBuildInfoId());
        archive.setSaleOrderInfoId(vo.getInstallSaveVo().getSaleOrderInfoId());
        archive.setBlueprintUrl(vo.getImageSaveVo().getDesignImg());
        archive.setPlaneGraphUrl(vo.getImageSaveVo().getPlanImg());
        archive.setUserEquipmentPhotoUrl(vo.getImageSaveVo().getAztpath1());
        archive.setBarCodeUrl(vo.getImageSaveVo().getAztpath2());

        List<String> installPhotoUrlList = new ArrayList<>();
        installPhotoUrlList.add(vo.getImageSaveVo().getAztpath3());
        installPhotoUrlList.add(vo.getImageSaveVo().getAztpath4());
        installPhotoUrlList.add(vo.getImageSaveVo().getAztpath5());
        installPhotoUrlList.add(vo.getImageSaveVo().getAztpath6());
        archive.setInstallPhotoUrl(String.join(";", installPhotoUrlList));

        this.saveOrUpdate(archive);
        Long id = archive.getId();
        return PageData.ok("id:" + id);
    }

    @Override
    public PageData getCustomerArchiveDetail(GetCustomerArchiveDetailVO vo, Integer getDetailType) throws Exception {
        // 查询档案详情
        CustomerArchiveDTO archivesDto = this.baseMapper.selectByCustomerId(vo.getCustomerId());
        // 组装工单信息
        Long installWorkOrderId = archivesDto.getInstallWorkOrderId();
        if (ObjectUtil.isNotNull(installWorkOrderId) && 1 == getDetailType) {
            archivesDto.setWorkOrderInstallDetail(null);
        }
        // 组装建筑信息
        Long buildInfoId = archivesDto.getBuildInfoId();
        if (ObjectUtil.isNotNull(buildInfoId)) {
            CustomerHouseDTO houseDetailDTO = customerHouseService.getHouseDetail(buildInfoId);
            archivesDto.setHouseDetail(houseDetailDTO);
        }
        // 组装设备信息
        Long saleOrderInfoId = archivesDto.getSaleOrderInfoId();
        if (ObjectUtil.isNotNull(saleOrderInfoId) && 1 == getDetailType) {
            GetSaleOrderDeatilsVO getSaleOrderDeatilsVO = new GetSaleOrderDeatilsVO();
            getSaleOrderDeatilsVO.setId(saleOrderInfoId);
            PageData pageData = saleOrderInfoService.getOrderDetail(getSaleOrderDeatilsVO);
            if (ObjectUtil.isNotNull(pageData) && 0 == pageData.getRetCode()) {
                archivesDto.setSaleOrderDetail(pageData.getData());
            }
        }

        // 返回图片信息
        // 设计图
        String blueprintUrl = archivesDto.getBlueprintUrl();
        String realBlueprintUrl = OssUtil.getImgSignURL(blueprintUrl, 1);
        archivesDto.setRealBarCodeUrl(realBlueprintUrl);

        // 平面图
        String planeGraphUrl = archivesDto.getPlaneGraphUrl();
        String realPlaneGraphUrl = OssUtil.getImgSignURL(planeGraphUrl, 1);
        archivesDto.setRealPlaneGraphUrl(realPlaneGraphUrl);

        // 户主设备合影
        String userEquipmentPhotoUrl = archivesDto.getUserEquipmentPhotoUrl();
        String realUserEquipmentPhotoUrl = OssUtil.getImgSignURL(userEquipmentPhotoUrl, 1);
        archivesDto.setRealUserEquipmentPhotoUrl(realUserEquipmentPhotoUrl);

        // 条形码/序列号
        String barCodeUrl = archivesDto.getBarCodeUrl();
        String realBarCodeUrl = OssUtil.getImgSignURL(barCodeUrl, 1);
        archivesDto.setRealBarCodeUrl(barCodeUrl);

        // 安装图
        String installPhotoUrl = archivesDto.getInstallPhotoUrl();
        List<String> installPhotoUrls = Arrays.asList(installPhotoUrl.split(";"));
        List<String> realInstallPhotoUrls = new ArrayList<>();
        for (String photoUrl : installPhotoUrls) {
            String realPhotoUrl = OssUtil.getImgSignURL(photoUrl, 1);
            realInstallPhotoUrls.add(realPhotoUrl);
        }
        String realInstallPhotoUrl = String.join(",", realInstallPhotoUrls);
        archivesDto.setRealInstallPhotoUrl(realInstallPhotoUrl);

        return PageData.ok("archivesDetail", archivesDto);
    }

    @Logs
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveImportInfo(ImportGovernmentalCustomerArchiveVO vo, CustomerSurveyExcel item) throws Exception {
        try {
            setItemAreaCode(item);
            // 1、保存二级客户信息
            String customerId = saveCustomerInfo(vo, item);
            // 2、保存客户的房屋信息
            String houseId = saveHouseInfo(vo, item, customerId);
            // 3、生成商机
            String opportunityId = saveOpportunity(vo, item, customerId,houseId);
            // 4、生成销售订单
            generateSaleOrderInfo(vo, item, customerId, houseId, opportunityId);
            // 保存项目和客户关系信息（导入的名单记录）
//            ProjectCustomerRelationship projectCustomerRelationship = new ProjectCustomerRelationship();
            // 由于前面保存商机信息的时候已经保存了项目-客户关系数据，所以此处先查询再更新
            ProjectCustomerRelationship projectCustomerRelationship = projectCustomerRelationshipService.queryProjectCustomerRelationship(customerId, vo.getProjectUuid());
            projectCustomerRelationship.setCustomerId(customerId);
            projectCustomerRelationship.setBusinessId(opportunityId);
            projectCustomerRelationship.setProjectUuid(vo.getProjectUuid());
            projectCustomerRelationship.setMainCustomerId(vo.getMasterCustomerId());
            projectCustomerRelationship.setMainFlag(0);
            projectCustomerRelationship.setMainBusinessId(vo.getMainBusinessId());
            projectCustomerRelationship.setImportBatch(vo.getOperateTimeStamp());
            projectCustomerRelationship.setDataType(0);
            projectCustomerRelationship.setDeleted(0);
            projectCustomerRelationship.setGmtCreateId(vo.getOperateUserId());
            projectCustomerRelationship.setGmtCreate(vo.getOperateDate());
            projectCustomerRelationshipService.saveOrUpdate(projectCustomerRelationship);
            log.info("导入客户名单，生成项目客户关系 -> {}", projectCustomerRelationship);
        } catch (Exception e) {
            throw e;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    @Logs
    public void updateImportInfo(ImportGovernmentalCustomerArchiveVO vo, CustomerSurveyExcel item) throws Exception {
        try {
            //1、保存行政区划
            setItemAreaCode(item);
            // 2、保存二级客户信息
            String customerId = saveCustomerInfo(vo, item);
            //根据用户id和项目uuid查商机id
            List<ProjectCustomerRelationship> list = projectCustomerRelationshipService.getRelationshipsExcludeMain(vo.getProjectUuid(), customerId);
            if (list.isEmpty()) {
                throw new Exception("根据用户id和项目uuid未能查出商机id!");
            }
            //3、更新商机id并更新商机所以信息
            ProjectCustomerRelationship projectCustomerRelationship = list.get(0);
            Opportunity opportunity = opportunityBusiness.getOpportunity(customerId, projectCustomerRelationship.getBusinessId());
            if (ObjectUtil.isNotNull(opportunity)) {
                vo.setOpportunityUuid(projectCustomerRelationship.getBusinessId());
            }
            String houseId = saveHouseInfo(vo, item, customerId);
            String opportunityId = saveOpportunity(vo, item, customerId,houseId);
            projectCustomerRelationship.setBusinessId(opportunityId);
            projectCustomerRelationship.setMainBusinessId(vo.getMainBusinessId());
            // 4、查询销售订单并更新销售订单内容
            List<SaleOrderInfo> saleOrderInfoList = saleOrderInfoService.getSale(customerId, opportunityId);
            if (CollUtil.isNotEmpty(saleOrderInfoList)) {
                SaleOrderInfo saleOrderInfo = saleOrderInfoList.get(0);
                vo.setHouseId(Long.parseLong(saleOrderInfo.getInstallInfoId()));
                vo.setSaleOrderId(saleOrderInfo.getId());
            }

            generateSaleOrderInfo(vo, item, customerId, houseId, opportunityId);
            // 保存项目和客户关系信息（导入的名单记录）//更新批次id
            projectCustomerRelationship.setImportBatch(vo.getOperateTimeStamp());
            projectCustomerRelationshipService.saveOrUpdate(projectCustomerRelationship);
        } catch (Exception e) {
            throw e;
        }
    }

    private String saveOpportunity(ImportGovernmentalCustomerArchiveVO vo, CustomerSurveyExcel item,
            String customerId,String houseId) throws Exception {
        SaveOpportunityBO saveOpportunityBO = new SaveOpportunityBO();
        saveOpportunityBO.setRelateOpportunityUuid(vo.getMainBusinessId());
        BeanUtils.copyProperties(vo, saveOpportunityBO);
        saveOpportunityBO.setXzqhdm(item.getAreaCode());
        saveOpportunityBO.setAddOpportunity(true);
        if (StrUtil.isNotEmpty(vo.getOpportunityUuid())) {
            saveOpportunityBO.setUuid(vo.getOpportunityUuid());
            vo.setOpportunityUuid(null);
            saveOpportunityBO.setAddOpportunity(false);
        }
        saveOpportunityBO.setOpportunityName(vo.getProjectName() + "-" + item.getContactName() + "-" + "生成商机");
        saveOpportunityBO.setOpportunityStage(OpportunityStageEnum._transaction);
        saveOpportunityBO.setOpportunityType(OpportunityTypeEnum._purchase);
        saveOpportunityBO.setProjectAddress(item.getAddress());
        if (StrUtil.isNotEmpty(item.getHousingArea())) {
            saveOpportunityBO.setProjectArea(new BigDecimal(item.getHousingArea()));
        }
        saveOpportunityBO.setBuildNature("新建");
        saveOpportunityBO.setBulidType("平房建筑");
        saveOpportunityBO.setCustomerId(customerId);
        saveOpportunityBO.setHouseId(houseId);
        saveOpportunityBO.setProjectRelationDataTypeEnum(ProjectRelationDataTypeEnum.EXCEL);
        saveOpportunityBO.setOpportunityClassification(OpportunityClassificationEnum.END_USRE);
        Opportunity opportunity = opportunityBusiness.save(saveOpportunityBO.convertToBO());
        log.info("导入客户名单，生成商机[{}]", opportunity.getUuid());
        return opportunity.getUuid();
    }

    @Override
    public Integer getArchiveCountByCustomerId(String customerId) {
        QueryWrapper<CustomerArchive> wrapper = new QueryWrapper<>();
        wrapper.eq("customer_id", customerId);

        return this.baseMapper.selectCount(wrapper);
    }

    // 设置行政区划编码
    private void setItemAreaCode(CustomerSurveyExcel item) throws Exception {
        if (StrUtil.isBlank(item.getAreaCode())) {
            throw new Exception("行政区划不能为空!");
        }

        // 设置行政区划代码
        String areaCode = Arrays.asList(item.getAreaCode().split("_")).get(0);
        item.setAreaCode(areaCode);
        // 设置经纬度
        Map<String, BigDecimal> coordinate = xzqhService.getCoordinate(areaCode);
        item.setLongitude(coordinate.get("longitude"));
        item.setLatitude(coordinate.get("latitude"));
    }

    // 保存客户基本信息
    private String saveCustomerInfo(ImportGovernmentalCustomerArchiveVO vo, CustomerSurveyExcel item) throws Exception {
        try {
            SaveCustomerVo saveCustomerVo = new SaveCustomerVo();
            BeanUtils.copyProperties(vo, saveCustomerVo);
            if (StrUtil.isNotEmpty(vo.getCustomerUuid())) {
                saveCustomerVo.setUuid(vo.getCustomerUuid());
                vo.setCustomerUuid(null);
            }
            saveCustomerVo.setCustomerName(item.getContactName());
            saveCustomerVo.setContact(item.getContactName());
            saveCustomerVo.setPhone(item.getContactPhone());
            saveCustomerVo.setCustomerNature(CustomerNatureEnum.END_USRE_GOVERNMENT.getKey()); // 先保存为政府客户,原因是为了在页面上展示【填写清洁取暖档案】按钮
            saveCustomerVo.setBusinessType(null); // 待定
            saveCustomerVo.setCustomerLevel(CustomerLevelEnum._level_2.getType());
            saveCustomerVo.setXzqhdm(item.getAreaCode());
            saveCustomerVo.setAddress(item.getAddress());
            saveCustomerVo.setLongitude(item.getLongitude());
            saveCustomerVo.setLatitude(item.getLatitude());
            saveCustomerVo.setSaveType(Integer.valueOf(CustomerSaveTypeEnum._my.getType()));
            saveCustomerVo.setSuperCustomerId(vo.getMasterCustomerId());
            saveCustomerVo.setMemo("从项目导入的客户,是二级客户");
            saveCustomerVo.setPlanYear(item.getPlanYear());
            saveCustomerVo.setIdCardNumber(item.getIdCardNumber());
            saveCustomerVo.setCustomerCode(null);
            saveCustomerVo.setEnergyUsePropertyCode(null);
            saveCustomerVo.setIsVillagers(StrUtil.isNotBlank(item.getIsVillagers()) && item.getIsVillagers()
                    .contains("1"));
            if (StrUtil.isNotBlank(item.getRemark())) {
                saveCustomerVo.setMemo(item.getRemark());
            }

            CustomerDTO customerDTO = crmCustomerService.saveCrmCustomer(saveCustomerVo);
            log.info("导入客户名单保存，生成用户[{}]", customerDTO.getUuid());
            return customerDTO.getUuid();
        } catch (Exception e) {
            log.error("保存客户基本信息失败,客户姓名:{},客户电话号:{},异常原因:{}", item.getContactName(), item.getContactPhone(), e.getMessage());
            throw e;
        }
    }

    // 保存客户房屋信息
    private String saveHouseInfo(ImportGovernmentalCustomerArchiveVO vo, CustomerSurveyExcel item,
            String customerId) throws Exception {
        CustomerHouseVO customerHouseVO = new CustomerHouseVO();
        BeanUtils.copyProperties(vo, customerHouseVO);
        if (ObjectUtil.isNotNull(vo.getHouseId())) {
            customerHouseVO.setId(vo.getHouseId());
            vo.setHouseId(null);
        }
        customerHouseVO.setCompanyId(vo.getOperateUserCompanyId());
        customerHouseVO.setCustomerId(customerId);
        customerHouseVO.setAreaCode(item.getAreaCode());
        customerHouseVO.setLongitude(item.getLongitude());
        customerHouseVO.setLatitude(item.getLatitude());
        customerHouseVO.setAddress(item.getAddress());
        customerHouseVO.setHouseNumber(item.getHouseNumber());
        customerHouseVO.setBuildingStructure(getAttributeCode(item.getBuildingStructure()));
        customerHouseVO.setHouseType(getAttributeCode(item.getHouseType()));
        customerHouseVO.setHeatingEnd(getAttributeCode(item.getHeatingEnd()));
        customerHouseVO.setEnergyType(getAttributeCode(item.getEnergyType()));
        customerHouseVO.setHeatingMode(getAttributeCode(item.getHeatingMethod()));
        // 设置默认值
        if (StrUtil.isNotEmpty(item.getHousingArea())) {
            customerHouseVO.setFloorSpace(new BigDecimal(item.getHousingArea()));
            customerHouseVO.setHeatingArea(new BigDecimal(item.getHousingArea()));
            customerHouseVO.setCommonHeatingArea(new BigDecimal(item.getHousingArea()));
        }
        customerHouseVO.setDesignHeatingLoad(DEFAULT_HEATING_LOAD); // 默认热负荷
        customerHouseVO.setIsVillage(null); // 是否农村
        try {
            CustomerHouse customerHouse = customerHouseService.saveHouseInfo(customerHouseVO);
            return String.valueOf(customerHouse.getId());
        } catch (Exception e) {
            log.error("保存客户房屋信息失败,客户姓名:{},客户电话号:{},异常原因:{}", item.getContactName(), item.getContactPhone(), e.getMessage());
            throw new Exception("保存客户房屋信息失败" + e.getMessage());
        }
    }


    // 获取属性编码
    private String getAttributeCode(String attribute) {
        String code = StrUtil.EMPTY;
        if (StrUtil.isBlank(attribute)) {
            return code;
        }
        try {
            List<String> list = Arrays.asList(attribute.split("_"));
            code = list.get(0);
        } catch (Exception e) {
            log.info("导入客户信息解析编码失败,失败原因:{}", e.getMessage());
        }
        return code;
    }

    // 生成销售订单
    private String generateSaleOrderInfo(ImportGovernmentalCustomerArchiveVO vo, CustomerSurveyExcel item,
            String customerId, String houseId, String businessId) throws Exception {
        // 获取推荐产品
        GGoodsDTO gGoodsDTO = recommendGoods(vo.getOperateUserCompanyId(), item.getEquipmentModel());
        if (ObjectUtil.isNull(gGoodsDTO)) {
            gGoodsDTO = recommendGoods(vo, item, houseId);
        }
        // 保存前置销售订单,取一个id
        String orderId = "";
        SaleOrderInfoVO saleOrderInfoVO_1 = new SaleOrderInfoVO();
        BeanUtils.copyProperties(vo, saleOrderInfoVO_1);
        if (ObjectUtil.isNotNull(vo.getSaleOrderId())) {
            saleOrderInfoVO_1.setId(vo.getSaleOrderId());
            vo.setSaleOrderId(null);
        }
        saleOrderInfoVO_1.setBusinessId(businessId);
        saleOrderInfoVO_1.setPriceSheetIdList(new ArrayList<>());
        saleOrderInfoVO_1.setSaleOrderName(item.getContactName() + "的销售订单");
        saleOrderInfoVO_1.setCommit(false); // 仅保存,不提交
        PageData pageData_1 = saleOrderInfoService.saveOrder(saleOrderInfoVO_1);
        if (ObjectUtil.isNotNull(pageData_1) && 0 == pageData_1.getRetCode()) {
            orderId = String.valueOf(pageData_1.getData().get("id"));
            if (StrUtil.isBlank(orderId)) {
                throw new Exception("保存前置销售订单失败");
            }
        }
        // 构造系统单
        SalePriceDetailVO salePriceDetailVO = new SalePriceDetailVO();
        salePriceDetailVO.setEquipmentId(gGoodsDTO.getSblx());
        salePriceDetailVO.setEquipmentName(gGoodsDTO.getGoodsName());
        salePriceDetailVO.setEquipmentModel(gGoodsDTO.getGoodsModel());
        salePriceDetailVO.setBrandId(String.valueOf(gGoodsDTO.getBrandId()));
        salePriceDetailVO.setCompanyId(gGoodsDTO.getCompanyId());
        salePriceDetailVO.setGuidePrice(gGoodsDTO.getPrice());
        salePriceDetailVO.setCount(1); // 默认1台
        salePriceDetailVO.setUnit(Integer.valueOf(gGoodsDTO.getUnit()));
        salePriceDetailVO.setType(0);
        salePriceDetailVO.setDiscount(100); // 折扣 100% -> 无折扣
        BigDecimal count = new BigDecimal(salePriceDetailVO.getCount());
        BigDecimal discount = new BigDecimal(salePriceDetailVO.getDiscount()).divide(new BigDecimal(100));
        salePriceDetailVO.setTotalPrice(count.multiply(salePriceDetailVO.getGuidePrice()).multiply(discount));
        List<SalePriceDetailVO> childList = new ArrayList<>();
        childList.add(salePriceDetailVO);
        SalePriceMasterVO salePriceMasterVO = new SalePriceMasterVO();
        BeanUtils.copyProperties(vo, salePriceMasterVO);
        List<Long> idList = salePriceService.getPriceSheetIdListByOrderId(Long.parseLong(orderId));
        if (!idList.isEmpty()) {
            salePriceMasterVO.setId(idList.get(0));
        }
        salePriceMasterVO.setOrderId(Long.valueOf(orderId));
        salePriceMasterVO.setChildList(childList);
        salePriceMasterVO.setCustomerId(customerId);
        salePriceMasterVO.setBuildId(houseId);
        salePriceMasterVO.setName("制热系统");
        salePriceMasterVO.setDiscount(100); // 折扣 100% -> 无折扣
        BigDecimal masterDiscount = new BigDecimal(salePriceMasterVO.getDiscount()).divide(new BigDecimal(100));
        salePriceMasterVO.setOtherCostPrice(BigDecimal.ZERO); // 其他费用默认为0
        salePriceMasterVO.setTotalOffer(childList.stream()
                .map(SalePriceDetailVO::getTotalPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        salePriceMasterVO.setTotalPrice(masterDiscount.multiply(salePriceMasterVO.getTotalOffer())
                .add(salePriceMasterVO.getOtherCostPrice()));
        salePriceMasterVO.setStatus(1); // 导入客户生成的销售订单默认状态为:1 -> 通过
        PageData pageData = salePriceService.addPriceSheet(salePriceMasterVO);
        if (Objects.isNull(pageData) || 0 != pageData.getRetCode() || Objects.isNull(pageData.getData())) {
            throw new Exception("保存系统单失败");
        }
        // 获取系统单id
        String priceMasterIdStr = String.valueOf(pageData.getData().get("id"));
        List<Long> priceSheetIdList = new ArrayList<>();
        priceSheetIdList.add(Long.valueOf(priceMasterIdStr));
        // 构造销售订单
        SaleOrderInfoVO saleOrderInfoVO = new SaleOrderInfoVO();
        BeanUtils.copyProperties(vo, saleOrderInfoVO);
        saleOrderInfoVO.setId(Long.valueOf(orderId));
        saleOrderInfoVO.setPriceSheetIdList(priceSheetIdList);
        saleOrderInfoVO.setBusinessId(businessId);
        saleOrderInfoVO.setCustomerId(customerId);
        saleOrderInfoVO.setPhone(item.getContactPhone());
        saleOrderInfoVO.setInstallAddress(item.getAddress());
        saleOrderInfoVO.setOrderType(2); // 相当于政府买鑫磊的产品，所以是政府订单
        saleOrderInfoVO.setStatus(2); // 默认支付成功
        saleOrderInfoVO.setPayModel(1); // 默认先安后付
        saleOrderInfoVO.setDiscount(100);
        BigDecimal orderDiscount = new BigDecimal(saleOrderInfoVO.getDiscount()).divide(new BigDecimal(100));
        saleOrderInfoVO.setOtherCostPrice(BigDecimal.ZERO);
        saleOrderInfoVO.setTotalOffer(salePriceMasterVO.getTotalPrice());
        saleOrderInfoVO.setTotalPrice(orderDiscount.multiply(saleOrderInfoVO.getTotalOffer())
                .add(saleOrderInfoVO.getOtherCostPrice()));
        saleOrderInfoVO.setCommit(true); // 直接提交
        saleOrderInfoVO.setAreaCode(item.getAreaCode());
        saleOrderInfoVO.setXzqhdm(item.getAreaCode());
        saleOrderInfoVO.setHouseId(houseId);

        PageData orderPageData = saleOrderInfoService.saveOrder(saleOrderInfoVO);

        if (0 == orderPageData.getRetCode()) {
            return String.valueOf(orderPageData.getData().get("id"));
        } else {
            log.error("生成订单信息失败,客户姓名:{},客户电话号:{},异常原因:{}", item.getContactName(), item.getContactPhone(), orderPageData.getRetMessage());
            throw new Exception("生成订单信息失败" + orderPageData.getRetMessage());
        }
    }

    // 推荐适用产品
    private GGoodsDTO recommendGoods(NullVO vo, CustomerSurveyExcel item, String houseId) throws Exception {
        /*CustomerHouse customerHouse = customerHouseService.getHouseInfo(houseId);
        if (Objects.isNull(customerHouse)) {
            throw new BusinessException("客户房屋信息不存在！");
        }*/
        // 查询客户房屋所需制热量
        BigDecimal needHeat = customerHouseService.getHouseNeedHeat(Long.valueOf(houseId));
        ImportGovernmentalCustomerArchiveVO ImportGovernmentalCustomerArchiveVO = (ImportGovernmentalCustomerArchiveVO) vo;
        // 查询设备类型对应的产品id列表
        /*   List<String> goodsIdList = gGoodsService.getGoodsIdListByEquipmentType(vo.getOperateUserCompanyId(), item.getEquipmentType());*/
        TProject project = tProjectService.getProjectDetail(ImportGovernmentalCustomerArchiveVO.getProjectId());
        if (project == null) {
            throw new Exception("此项目没有添加设备类型");
        }
        String[] parts = project.getDeviceModels().split(";");
        List<String> goodsIdList = Arrays.asList(parts);
        // 查询产品制热量
        String paramName = "制热量";
        BigDecimal paramValue = BigDecimal.ZERO;
        GGoodsDTO gGoodsDTO = null;
        boolean flag = Boolean.TRUE;
        for (String goodsId : goodsIdList) {
            // 查询产品详情
            GGoodsDTO dto = null;
            try {
                dto = gGoodsService.getGoodsDetailSblx(goodsId, vo.getOperateUserCompanyId());
                if (ObjectUtil.isNull(dto)) {
                    continue;
                }
            } catch (Exception e) {
                continue;
            }
            // 记录第一个产品
            if (flag) {
                gGoodsDTO = dto;
                paramValue = outputParamValue(gGoodsDTO, paramName);
                flag = Boolean.FALSE;
                continue;
            }
            // 比较后面的产品
            BigDecimal heatingCapacity = outputParamValue(dto, paramName);
            BigDecimal oldDiffValue = needHeat.subtract(paramValue).abs();
            BigDecimal newDiffValue = needHeat.subtract(heatingCapacity).abs();
            if (newDiffValue.compareTo(oldDiffValue) < 0) {
                paramValue = heatingCapacity;
                gGoodsDTO = dto;
            }
        }
        if (Objects.isNull(gGoodsDTO)) {
            throw new Exception("未获取到适用产品");
        }
        return gGoodsDTO;
    }

    // 输出产品的指定指标
    private BigDecimal outputParamValue(GGoodsDTO dto, String paramName) {
        BigDecimal paramValue = BigDecimal.ZERO;

        List<IsSblxNameplateConfigDTO> fieldsParamList = dto.getFieldsParamList();
        // 检查有无铭牌
        if (CollectionUtil.isEmpty(fieldsParamList)) {
            return paramValue;
        }
        // 检查有无指定指标
        IsSblxNameplateConfigDTO configDTO = fieldsParamList.stream()
                .filter(n -> paramName.equals(n.getSblxFieldDesc()))
                .findFirst()
                .orElse(null);
        if (Objects.isNull(configDTO)) {
            return paramValue;
        }
        // 返回指定指标值
        return StrUtil.isBlank(configDTO.getValue()) ? paramValue : new BigDecimal(configDTO.getValue());
    }

    // 按导入的设备型号查询具体产品信息
    private GGoodsDTO recommendGoods(String companyId, String equipmentModel) throws Exception {
        if (StrUtil.isBlank(equipmentModel) || !equipmentModel.contains("_")) {
            throw new Exception("按照当前导入设备型号未能查询具体产品信息");
        }
        // 获取设备型号编码
        String goodsCode = Arrays.asList(equipmentModel.split("_")).get(0);

        return gGoodsService.getGoodsDetailByGoodsCode(companyId, goodsCode);
    }

}
